const dayjs = require('dayjs')
let users = [] //正在登录的集合
let count = 0
const {
	nanoid
} = require('nanoid');
const {
	reduce
} = require("./utils/common.js")
require('./live')
const fun = (redisClient, io, db) => {
	//用户连接相关
	const userConnect = async (userid, username, socket) => {
		await redisClient.select(0) //默认0
		//判断用户是否登录socket
		if (!userid) return
		let infoStr = JSON.stringify({
			userid: userid,
			username: username
		})
		//根据id去重
		let menber = await redisClient.SMEMBERS(`user:userinfo:${userid}`)
		let menberJson = eval("[" + menber + "]")
		let ismenber = menberJson.some(user => user.userid == userid)
		let userList = null,
			self = []
		if (!ismenber) {
			//根据当前用户的username_id存储当前用户的聊天好友
			await redisClient.SADD(`user:userinfo:${userid}`, infoStr)

			//从redis获取用户信息
			userList = await redisClient.SMEMBERS(`user:userinfo:${userid}`)

			self = eval("[" + userList + "]")
		} else {
			self = menberJson
		}
		// const userinfo = self.find(user => user.userid === userid)
		// userinfo.id = socket.id

		const userinfo = users.find(user => user.userid === userid)
		if (userinfo) {
			userinfo.id = socket.id
		} else {
			users.push({
				id: socket.id,
				username,
				userid
			})
		}
		io.emit('online', {
			users,
			self
		})
		//断线
		socket.on("disconnect", () => {
			let i = users.findIndex(v => v.userid == userid)
			let newUsers = users.splice(i, 1)
			io.emit('online', {
				users: users,
				self
			})
		});
	}
	// 单聊
	const singleChat = async (userid, username, socket) => {
		//获取聊天记录
		socket.on(`getMsg`, async (msg) => {
			await redisClient.select(1) //
			let msgList = await redisClient.LRANGE(`chat:msg:${msg.userid}:${msg.receiveid}`, 0,
				-1)
			let msgListJson = eval("[" + msgList + "]")
			let selfMsg = []
			//获取用户对应的聊天数据
			for (let i in msgListJson) {
				if (
					(msgListJson[i].userid == msg.userid && msgListJson[i]
						.receiveid ==
						msg.receiveid) ||
					(msgListJson[i].userid == msg.receiveid && msgListJson[
							i]
						.receiveid == msg.userid)
				) {
					selfMsg.push(msgListJson[i])
				}
			}
			socket.emit(`getMsg`, selfMsg)
		})
		//监听发送事件
		socket.on('send_msg', async (msg) => {
			await redisClient.select(1) //
			const toUser = users.find(user => user.userid === msg.receiveid)
			//离线推送
			let data = {
				...msg,
				time: dayjs().format('YYYY-MM-DD HH:mm:ss')
			}
			//存储指定用户
			if (data.type !== 3) {
				await redisClient.rPush(`chat:msg:${msg.receiveid}:${msg.userid}`, JSON
					.stringify(
						data))
				await redisClient.rPush(`chat:msg:${msg.userid}:${msg.receiveid}`, JSON
					.stringify(data))
			}

			if (toUser === undefined) return
			//发送指定用户
			socket.to(toUser.id).emit('receive', data)
		})

		socket.on('confirm', msg => {
			const toUser = users.find(user => user.userid == msg.receiveid)
			if (toUser === undefined) return
			socket.to(toUser.id).emit('confirm', {
				...msg
			})
		})
		//视频(拒绝)
		socket.on('onRefuse', (msg) => {
			const toUser = users.find(user => user.userid == msg.receiveid)

			if (toUser === undefined) return
			socket.to(toUser.id).emit('onRefuse', {
				...msg
			})
			/* socket.emit('onRefuse', {
				...msg
			}) */
		})
		//视频(同意)
		socket.on('onAccept', (msg) => {
			const toUser = users.find(user => user.userid == msg.receiveid)
			if (toUser === undefined) return
			socket.to(toUser.id).emit('onAccept', {
				...msg
			})
			/* socket.emit('onAccept', {
				...msg
			}) */
		})
		//清空聊天记录
		socket.on('clearChat', async (msg) => {
			await redisClient.select(1) //
			await redisClient.DEL(`chat:msg:${msg.userid}:${msg.receiveid}`)
		})
	}

	//直播
	const liveChat = async (userid, username, socket) => {
		//创建直播
		socket.on('create_live', async (msg) => {
			msg.id = nanoid()
			msg.createtime = dayjs().format('YYYY-MM-DD HH:mm:ss')
			msg.userid = userid
			msg.username = username
			const collection = db.collection('lives_room')
			const findResult = await collection.find({
				userid: userid
			}).toArray()
			if (findResult.length > 0) return socket.emit('lives_err', '请勿重复创建')
			await collection.insertOne(msg)
			socket.emit('create_live', msg)
		})
		socket.on('get_lives_list', async (msg, condition = {}) => {
			const collection = db.collection('lives_room')
			const findResult = await collection.find(condition).toArray();
			socket.emit('get_lives_list', findResult)
		})
		//获取直播信息
		socket.on('get_lives_info', async (msg) => {
			const collection = db.collection('lives_room')
			const findResult = await collection.find({
				userid: msg.userid
			}).toArray();
			socket.emit('get_lives_info', findResult.length ? findResult[0] : {})
		})
		//存储sdp
		socket.on('send_offer', async (msg, offer) => {
			const collection = db.collection('lives_room')
			await collection.updateOne({
				userid: msg.userid
			}, {
				$set: {
					offer: offer
				}
			})
			const findResult = await collection.find({
				userid: msg.userid
			}).toArray();
			socket.emit('get_lives_list', findResult)
		})
		// 直播
		socket.on('send_lives_msg', async (msg) => {
			let data = {
				...msg,
				time: dayjs().format('YYYY-MM-DD HH:mm:ss')
			}

			io.sockets.in(msg.crowd_id).emit('send_lives_msg', msg)
		})

		socket.on('live_join', (roomMsg) => {
			count++
			socket.join(roomMsg.crowd_id)
			io.sockets.in(roomMsg.crowd_id).emit('join', {
				...roomMsg,
				count: count
			}); //包括自己
		})
		socket.on('live_leave', function(roomMsg) {
			count--
			io.sockets.in(roomMsg.crowd_id).emit('live_leave', {
				...roomMsg,
				count: count
			}); //包括自己
			//用户离开房间
			// socket.leave(roomMsg.id)
		})

	}
	//聊天功能操作相关
	const chrtSetting = async (userid, username, socket) => {
		//申请入群
		await redisClient.select(1) //默认1
		socket.on('applyCrowd', async (msg) => {
			let menber = await redisClient.SADD(`crowdchat:apply:${msg.leaderid}`, JSON
				.stringify(msg))
			const toUser = users.find(user => user.userid === msg.leaderid)
			if (toUser === undefined) return
			socket.to(toUser.id).emit('receive', msg)
		})
		//获取申请列表
		socket.on('getApplyCrowd', async (userid) => {
			let menber = await redisClient.SMEMBERS(`crowdchat:apply:${userid}`)
			let msgListJson = eval("[" + menber + "]")
			socket.emit(`getApplyCrowd`, msgListJson)
		})
		//拒绝
		socket.on('applyCrowdRefuse', async (msg) => {
			let msgData = JSON.parse(msg)
			await redisClient.SREM(`crowdchat:apply:${msgData.leaderid}`, msg)
		})
		//同意
		socket.on('applyCrowdAgree', async (userid) => {
			await redisClient.SREM(`crowdchat:apply:${userid}`)
		})
	}
	//点赞评论历史记录
	const comment = async (userid, username, socket) => {
		await redisClient.select(1) //默认1
		socket.on('likeComment', async (msg) => {
			delete msg.isdz
			await redisClient.SADD(`like:comment:${msg.articleid}:${msg.userid}`, JSON
				.stringify(msg))
			await redisClient.SADD(`like:myComment:${msg.reviewerid}`, JSON.stringify(msg))
		})
		socket.on('getLikeComment', async (ids) => {
			await redisClient.select(1) //
			let msgList = await redisClient.SMEMBERS(
				`like:comment:${ids.articleid}:${ids.userid}`)
			let msgListJson = eval("[" + msgList + "]")
			socket.emit(`getLikeComment`, msgListJson)
		})
		socket.on('getMyLikeComment', async (id) => {
			await redisClient.select(1) //默认1
			let msgList = await redisClient.SMEMBERS(`like:myComment:${id}`)
			let msgListJson = eval("[" + msgList + "]")
			socket.emit(`getMyLikeComment`, msgListJson)
		})
		socket.on('delLikeComment', async (msg) => {
			delete msg.isdz
			await redisClient.select(1) //
			await redisClient.SREM(`like:comment:${msg.authorid}`, JSON.stringify(msg))
		})
		//添加历史浏览记录
		socket.on('historyRecord', async (info) => {
			delete info.heat
			await redisClient.select(1)
			await redisClient.SADD(`record:${userid}`, JSON.stringify(info))

		})
		socket.on('getHistoryRecord', async () => {
			await redisClient.select(1)
			let msgList = await redisClient.SMEMBERS(`record:${userid}`)
			let msgListJson = eval("[" + msgList + "]")
			socket.emit(`getHistoryRecord`, msgListJson)
		})
		//历史访问用户记录
		socket.on('historyUserRecord', async (info) => {
			if (info.userid == userid) return
			await redisClient.select(1)
			await redisClient.SADD(`record_user:${userid}`, JSON.stringify({
				userid: info.userid,
				username: info.username,
				handimg: info.handimg,
				time: new Date().getTime()
			}))

		})
		socket.on('getHistoryUserRecord', async () => {
			await redisClient.select(1)
			let msgList = await redisClient.SMEMBERS(`record_user:${userid}`)
			let msgListJson = eval("[" + msgList + "]")
			msgListJson = reduce(msgListJson, 'userid')
			socket.emit(`getHistoryUserRecord`, msgListJson)
		})
	}
	/* 
		insertMany insertOne 插入
		find({}) 查询 findOne 	find({}).toArray();
		deleteOne deleteMany
		updateOne(query,update ) updateMany {name: 'xxx'},[{$set: {name: 'xxx1'}}]
	 */
	// 群聊
	const crowdChat = async (userid, username, socket) => {
		const collection = db.collection('crowdChat')
		socket.on('join', async (roomMsg) => {
			socket.join(roomMsg.crowd_id)
			io.sockets.in(roomMsg.crowd_id).emit('join', roomMsg); //包括自己
		})
		socket.on('get_room_msg', async (msg) => {
			const findResult = await collection.find({}).toArray();
			socket.emit('get_room_msg', findResult)
		})
		socket.on('send_room_msg', async (msg) => {
			let data = {
				...msg,
				time: dayjs().format('YYYY-MM-DD HH:mm:ss')
			}
			await collection.insertOne(data)
			io.sockets.in(msg.crowd_id).emit('send_room_msg', msg)
		})
		socket.on('leave', function(roomMsg) {
			//用户离开房间
			// socket.leave(roomMsg.crowd_id)
		})
		socket.on('clear_romm_msg', async (msg) => {

		})
	}

	(async function() {
		io.on("connect", async (socket) => {
			const userid = socket.handshake.query.userid
			const username = socket.handshake.query.username
			//redis相关
			userConnect(userid, username, socket) //用户连接相关
			singleChat(userid, username, socket) //单聊
			liveChat(userid, username, socket) //直播
			chrtSetting(userid, username, socket) //聊天功能操作相关
			comment(userid, username, socket) //点赞评论
			//mongodb相关
			crowdChat(userid, username, socket) //群聊

		})
	})()
	// httpServer.listen(100)
}
module.exports = fun